import React ,{useEffect , useState}from 'react'
import { Menu } from 'antd';
import { Link ,useLocation } from "umi"
import menusConfig from '../config/menuConfig'
import { Menus } from '../config/menuConfig'
import * as Icon from "@ant-design/icons";
import { useSelector, useDispatch } from "umi"
// import { Link ,useLocation  } from "react-router-dom"
type Props = {}




const menu = (props: Props) => {
    const [pathName, setPathName] = useState(['/home/index'])
    const location = useLocation()

    useEffect(() => { setPathName([location.pathname]) }, [location])

    // const menuState = useSelector((state: { menuData: {} }) => {
    //     //state整个仓库i数据，product是仓库命名空间
    //     return state.menuData
    // })
    const dispatch = useDispatch();


    const initMenu = (list: any) => {
        return list.map((item: any) => {
            //判断用户权限里面是否存 子菜单
            // if(role.menus.indexOf(item.key)!=-1){
            //判断是否为一级菜单
            if (!(item as any).children) {
                return (
                    <Menu.Item onClick={() => add(item)} key={item.key} icon={item.icon ? iconToElement(item.icon) : ""}>
                        <Link to={item.key}>{item.title}</Link>
                    </Menu.Item>
                )
            } else {
                return (
                    <Menu.SubMenu key={item.key} icon={item.icon ? iconToElement(item.icon) : ""} title={item.title}>
                        {initMenu(item.children)}
                    </Menu.SubMenu>
                )
            }
            // }

        })
    }

    // 创建icon图标元素
    const iconToElement = (name: string) =>
        React.createElement(Icon && (Icon as any)[name], {
            style: { fontSize: '16px' }
        })

    const add = (item: any) => {
        // console.log("menu", item);
        dispatch({
            type: "menuData/query",
            payload: item
        })
    }

    return (
        <Menu
            theme="dark"
            mode="inline"
            defaultSelectedKeys={pathName}
            selectedKeys={pathName}
            defaultOpenKeys={['/marketing']}
        // nowMenu={nowMenu}

        >
            {initMenu(menusConfig)}

        </Menu>
    )
}

export default menu